package com.wise.service.cms.content.menu;

import cn.hutool.core.collection.CollectionUtil;
import com.wise.entities.content.Menu;
import com.wise.framework.dao.SqlSelect;
import com.wise.framework.daoannotations.Table;
import com.wise.framework.daomodel.DaoList;
import com.wise.framework.daomodel.DaoOne4Update;
import com.wise.framework.daomodel.DaoRemove;
import com.wise.framework.validation.Precondition;
import com.wise.summer.v1.cms.content.menu.DeleteMenuById;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.wise.model.content.ContentErrMsgs.Err_000500000019;
import static com.wise.model.content.ContentErrMsgs.Err_000500000020;

@Service
@SummerService
public class DeleteMenuService implements SummerServiceBean<DeleteMenuById> {

	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Override
	public void sum(DeleteMenuById model) {
		Menu menu = DaoOne4Update.s(Menu.class, model.getId(), Err_000500000020);
		if (StringUtils.isEmpty(menu.getParentId())) {
			//如果被删除的菜单没有父菜单id，则为父菜单，删除对应的子菜单
			SqlSelect sql = SqlSelect.selec("*");
			sql.fromClassName(Menu.class);
			sql.eq(Menu._parentId, menu.getId());
			List<Menu> menus = DaoList.s(Menu.class, sql);
			List<String> idList = null;

			if (CollectionUtil.isNotEmpty(menus)){
				idList = menus.stream().map(Menu::getId).collect(Collectors.toList());
			}
			if (CollectionUtil.isNotEmpty(idList)){
				Table menuTable = Menu.class.getAnnotation(Table.class);

				//执行删除
				MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource();
				mapSqlParameterSource.addValue("id", idList);
				namedParameterJdbcTemplate.update("delete from "+menuTable.value()+" where id in (:id)", mapSqlParameterSource);
			}

		}
		//删除菜单
		DaoRemove.s(menu);
		model.setSummerResult(true);
	}
}
